<template>
  <div class="pai">
    <nav_bar title='快速识别' background='#fff' ></nav_bar>
    <div class="tip"  v-if="newMsg">
            <form name='pushMsgFm' report-submit @submit='orderSign' class="tepForm" >
              <button form-type="submit"  class="commit">
                  你有新消息，请点击查看！
              </button>
          </form>
        </div>
    <div class="upLoad" @click="uploadImg">
      <img src="../../../static/images/icon/pai1.png" class="baseImg" >
      <!-- <div>快速识别</div> -->
    </div>

    <!-- 图片列 -->
    <div class="imgList">
      <div  v-for="(item,index) of historyData" :key="index">
        <van-swipe-cell :right-width="60" :left-width="0" disabledLeft>
            <van-cell-group>
              <div class="imgItem">
                <div class="img_wrapper">
                  <img :src="item.result_thumb_url?item.result_thumb_url:item.result_img_url" alt="" @click="prevImg(item.result_img_url)" mode="aspectFill">
                  <div class="img_layer" v-show="item.status==0">识别中</div>
                </div>
                <div class="item-left">
                  <div class="item-left-num">{{item.result_point_num}}</div>
                  <div class="item-left-time">{{item.created_at}}</div>
                </div>
              </div>
            </van-cell-group>
              <div slot="right" class="slot-right"><div @click="deletePai(item,index)" class="slot-right-btn">删除</div></div>
          </van-swipe-cell>
      </div>
    </div>

    <!-- 弹窗 -->
    <van-dialog
  use-slot
  close-on-click-overlay
  confirm-button-color="#1989fa"
  cancel-button-color="#1989fa"
  title="请选择下一步操作"
  :show="showDialog"
  show-cancel-button
  confirmButtonText="涂鸦"
  cancelButtonText="直接识别"
  @confirm="toPaint"
  @cancel="commit"
  @close="showDialog=false"
  @getuserinfo="getUserInfo"
>
<div style="width:100%;height:40px"></div>
</van-dialog>
  </div>
</template>
<script>
import {mapState,mapActions} from 'vuex';
export default {
  name:'pai',
  data() {
    return {
      showDialog:false,
      img_url:'',//涂鸦前的图片id
      img_id:'',
      img_id_paint:'',//涂鸦后的图片id
      width:'',
      height:'',//涂鸦的宽高

      newMsg:'',
      historyData:[],
      page:1,
      startGetnewsTimer:''
    }
  },
  computed: {
    ...mapState({
      //h5传来的图片信息
      imgData:state =>state.modulesProject.imgData
    }),
    count:{
      set:function(val){
        this.$store.dispatch('setCount',val);
      },
      get:function(){
        return this.$store.state.modulesProject.count
      }
    }
  },
  watch: {
    imgData(nval){
      if(nval){
        this.img_url=nval[0].imgUrl;
        this.img_id_paint=nval[0].imgId;
        this.width=nval[0].width;
        this.height=nval[0].height;
      }
    }
  },
  methods: {
    ...mapActions(['setImgData']),
    async deletePai(item,index){
      //删除
     let judge=await this.$currency.showModal('确认删除?','')
     let userToken=wx.getStorageSync('userToken')
     if(judge){
       let res= await this.$request.postData('/ucenter/delOneShotAnonPoint',{
         id:item.id,
         user_token:userToken
       })
       this.$currency.showToast(res.data.message)
       if(res.data.level=='success'){
           this.historyData.splice(index,1);
           this.$forceUpdate()
       }
     }
    },
    prevImg(url){
      wx.previewImage({
          current: url, // 当前显示图片的http链接
          urls: [url] // 需要预览的图片http链接列表
        })
    },
    async uploadImg(){
      var userToken=wx.getStorageSync('userToken')
      if(!userToken){
        this.$currency.navigateTo('/pages/login/main')
      } else{
        let res = await this.$request.getData('/auth/whetherPerfectLoginInfo',{user_token:userToken});
        if (res.data.level == 'success'){
          this.startGetnews()
          let res=await this.$currency.upLoadImage(this)
          const data=JSON.parse(res.data);
          const img_url=data.data.img_url;
          this.img_url=img_url;
          this.img_id=data.data.id;
          if(res){
            this.showDialog=true
          }
        } else{
          this.$currency.showToast(res.data.message,'none',2500)
        }
      }
    },
    toPaint(){
      //跳转涂鸦页面
      this.$currency.redirectTo(`/pages/drawImg/main?imgUrl=${this.img_url}&imgId=${this.img_id}`)
    },
    commit(){
      //直接提交
      this.showDialog=false;
      this.submit()
    },
    async submit(){
      const userToken=wx.getStorageSync('userToken');
      try {
        const res=await this.$request.postData('/ucenter/OneShotAnonPoint',{
          img_id:this.img_id_paint||this.img_id,
          graffiti_before_img_id:this.img_id,
          width:this.width,
          height:this.height,
          user_token:userToken
        },{show:true,title:'识别中，请稍等',mask:true})
        this.$currency.showToast(res.data.message);
        if(res.data.level=='success'){
          this.orderSign()
        }
      } catch (error) {
        this.$currency.showToast('系统打了个盹，请稍后再操作');
      }
    },
    async getHistory(){
      //获取列表
      const userToken=wx.getStorageSync('userToken');
      const res=await this.$request.getData('/ucenter/getOneShotAnonPointList',{
        user_token:userToken,
        page:this.page,
        limit:8
      })
      if(res.data.level=='success'){
        let lastData=this.historyData;
        this.historyData=[...lastData,...res.data.data];
        wx.stopPullDownRefresh()
      }
    },
    async startGetnews(){
        //轮询获取新消息s
        const _this=this
        async function timerFn () {
          const userToken=wx.getStorageSync('userToken')

          const data=await _this.$request.getData('/ucenter/oneShotStatusUpdate',{
            user_token:userToken
          },{show:false})
          if(data.data.data!='no'){
            _this.newMsg=true;
            setTimeout(()=>{
              _this.newMsg=false;
            },5000)
            _this.updatePaiList(data.data.data)
          }
        _this.startGetnewsTimer=  setTimeout(timerFn, 1500)
        }
        timerFn()
      },
      updatePaiList(data){
        //更新数据
        let list=this.historyData;
       let index= list.findIndex((item,index)=>{
          return item.id==data.id
        })
        if(!isNaN(index)){
          this.historyData.splice(index,1,data);
        }
      },
      orderSign(){
        //刷新
        this.initData();
        this.page=1;
        this.historyData=[]
        this.getHistory()
        this.newMsg=false
        // this.recordState()
      },
      recordState(){
        //点击新消息后触发
        const userToken=wx.getStorageSync('userToken')
        const res=this.$request.postData('/ucenter/cancelOneShotStatus',{
          user_token:userToken
        })
      },
    initData(){
      this.img_url='';
      this.img_id='';
      this.graffiti_before_img_id='';
      this.height='';
      this.width='';
      this.showDialog=false;
      this.setImgData('')
    }
  },
  onLoad(){
    this.historyData=[];
    this.page=1;
    this.startGetnews();
    this.getHistory();
    setTimeout(()=>{
      if(this.imgData){
        this.submit()
      }
    },1000)
  },

  onReachBottom(){
    this.page++;
    this.getHistory();
  },
   onPullDownRefresh() {
     this.historyData=[];
     this.page=1;
     this.getHistory();
  },
  onHide(){
    clearTimeout(this.startGetnewsTimer);
    this.newMsg=''
  },
  onUnload(){
    clearTimeout(this.startGetnewsTimer)
    this.newMsg=''
  }
}
</script>
<style lang="scss" scoped>
  $base-color:#f28b00;
  .pai{
    width: 100%;
    position: relative;
    overflow: hidden;
  }
  .num{
    display: flex;
    align-items: center;
    padding:20px;
    border-bottom: 1px solid #eee;
    margin-bottom: 10px;
  }
  .upLoad{
    width: calc(100% - 20px);
    margin-left: 10px;
    border:2px solid #eee;
    background: #fff;
    border-radius: 10px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    height: 200px;
    position: fixed;
    z-index: 10;

    .baseImg{
      width: 120px;
      height: 120px;
    }
    div{
      margin:10px 0;
      font-weight: 800;
      font-size: 20px;
    }
  }

  // 图片列
  .imgList{
    margin-top:250px;
    padding:0 10px
  }
  .cell-wrapper{
    width: 100%
  }
  .img_wrapper{
      position: relative;
      width: 150px;
      height: 100px;
      line-height: 100px;
    }
    .img_layer{
       position:absolute;
       top:0;
      z-index:9;
      color:#fff;
      text-align: center;
      width: 150px;
      height: 100%;
      background: rgba($color: #000000, $alpha: 0.7);
      border-radius: 10px;
    }
  .imgItem{
    margin:20px 0;
    padding: 5px;
    border-radius: 10px;
    border:1px solid #eee;
    display: flex;
    height: 100px;
    img{
      width:100%;
      height: 100%;
      border-radius: 10px;
    }
    .item-left{
      height: 100%;
      margin-left:10px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .item-left-num{
        font-weight: 600;
        color:green;
        font-size: 16px
      }
      .item-left-time{
        font-size: 12px;
      }
    }
  }

  .tip{
  position: fixed;
  width: 100%;
  z-index: 99;
  button{
    color:#ff3366;
    font-size: 14px;
  }

}
</style>
<style>
  .slot-right{
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  color:#fff;
  background: red;
}
.slot-right-btn{
    width:100%;
    text-align: center;
    height: 100%;
    line-height: 100px
  }
</style>
